
import os, os.path

class video:
  title = None

  def __init__(self,filename):
    self.filename = filename
    self.filetype = unicode(filename.split(".")[-1])
    self.size, self.episode, self.season, self.episode_title = 0,0,0,"NOT TV"
    self.build(filename)

  def build(self,filename):
    if is_tv(filename):
      self.gather_tv_data(filename)
    else:
      self.gather_movie_data(filename)

  def gather_movie_data(self,filename):
    fn = os.path.split(filename)[1] #So we only search on the actual file name #TV case #1, most common, seen in Its Always Sunny if re.search("S[0-9][0-9]*E[0-9][0-9]",fn):
    import imdb
    import re
    from fuzzywuzzy import fuzz
    #i = imdb.IMDb('sql',uri='sqlite:///C:\Users\peter\code\imdb.sql',useORM=['sqlalchemy'])
    i = imdb.IMDb()
    self.type = "Movie"
    j = -1 
    movies = i.search_movie(fn)
    if movies:
      for movie in i.search_movie(fn):
        if fuzz.partial_ratio(movie["title"],filename) > j:
          j = fuzz.partial_ratio(movie["title"],filename)
          m = movie
      self.title = m["title"]
      self.movie = m
    else:
      raise IMDB_error(fn)
      self.title = "unkown"
    
  def gather_tv_data(self,filename):
    import imdb
    import re
    i = imdb.IMDb()
    fn = os.path.split(filename)[1] #So we only search on the actual file name
    #TO DO grab season number from folder if avaliable
    self.get_tv_show()
    self.type = "TV"
    string = re.findall("[^0-9]?[0-9]?[0-9][^0-9][0-9][0-9][^0-9]",fn)[-1]
    self.season = int(filter(None,re.split("[^0-9]",string))[0])#first splits up the string into an array with empty strings and the episode/season numbers, then selects the season
    self.episode = int(filter(None,re.split("[^0-9]",string))[1])
    i.update(self.movie,"episodes")
    if self.movie.has_key("episodes"):
        self.episode_title = self.movie["episodes"][self.season][self.episode]["title"] #episodes returns an array of episodes, first by season then by episode
    else:
      raise IMDB_error("unable to fetch episodes for " + str(self.movie))

  def get_tv_show(self):
    import imdb
    import re
    i = imdb.IMDb()
    fn = os.path.split(self.filename)[1]
    string = re.split("[^0-9]?[0-9]?[0-9][^0-9][0-9][0-9][^0-9]",fn)[0] #removes the episode/season counter
    string = re.sub("^[^A-Za-z]*","",string) #removes anything at the start thats not an alphabetical character
    print "searching imdb with: " + string
    self.movie = select_tv_show(i.search_movie(string),self.filename)
    if self.movie:
        self.title = imdb_en_title(self.movie)
        self.id = self.movie.movieID
    else:
      raise IMDB.error("failed to select a movie for: " + self.filename)

  def __str__(self):
    return self.filetype

  def to_db(self):
    return self.filename,self.filetype,self.title,self.season,self.episode,self.episode_title,self.size

#TODO clean the string better
def clean(string):
  return string

def imdb_episode_title(data):
  i = imdb.IMDb('sql',uri='sqlite:///C:\Users\peter\code\imdb.sql',useORM=['sqlalchemy'])
  m = i.search_movie(str(data["show"]))[0]
  print "movie:" + str(m)
  i.update(m,"episodes")
  if "episodes" in m:
    self.episode_title = m["episodes"][self.season][self.episode]["title"]
  else:
    raise Movie_data_error("Failed to retrive episode title data for show " + self.title + "S" + str(self.season) + "E" + str(self.episode))

def is_tv(filename):
    import re
    if re.search("Season [0-9]+",filename): return True
    #This regex will match anything like S01E02 or 01.02 or 02x03, may need to be rewritten if false positive crop up
    if re.search("[^0-9][0-9]?[0-9][^0-9][0-9][0-9][^0-9]",filename): return True
    return False

  #TODO: needs to be fixed for stuff like let the right one in
def imdb_en_title(movie):
  return movie["title"]

def select_tv_show(movies,filename=""):
  m = None
  if filename == "":
    for movie in movies:
      print "considering:" + str(movie)
      if movie["kind"] == "tv series":
        print "selecting:" + str(movie)
        return movie
  else:
    from fuzzywuzzy import fuzz
    i = 0
    for movie in movies:
      if fuzz.partial_ratio(movie["title"],filename) > i and movie["kind"] == "tv series":
        i = fuzz.partial_ratio(movie["title"],filename)
        m = movie
  if m: return m
  raise IMDB_error("filename")

class IMDB_error(Exception):
  def __init__(self,value):
    self.parameter = value
  def __str__(self):
    return repr(self.parameter)

class Movie_data_error(Exception):
  def __init__(self,value):
    self.parameter = value
  def __str__(self):
    return repr(self.parameter)


